import json
import datetime


class DatetimeEncoder(json.JSONEncoder):
    def default(self, obj):
        obj = datetime.datetime.strftime(obj, '%Y-%m-%d %H:%M:%S')
        return obj


class DatetimeDecoder(json.JSONDecoder):
    def decode(self, s):
        s = json.loads(s)
        time = s.pop('now')
        time = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
        s['now'] = time
        return s


class PersonEncoder(json.JSONEncoder):
    def default(self, obj):
        return {'name': obj.name, 'age': obj.age}


class PersonDecoder(json.JSONDecoder):
    def decode(self, s):
        s = json.loads(s)
        person = s.pop('person')
        person = Person(**person)
        s['person'] = person
        return s


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


data = json.dumps({
    "int": 111,
    "float": 3.1415,
    'str': '你好',
    'list': [1, 2, 3],
    'tuple': (1, 2, 3),
    # 'collection':{1,2,2}, 集合不能被序列化
    'dict': {'name': 111},
    'bool': True,
    'none': None,
    # 'now': datetime.datetime.now(),
    'person': Person('zdz', 22)
}, ensure_ascii=False, cls=PersonEncoder)

# print(data)

r = json.loads(data, cls=PersonDecoder)
print(r)
